<!-- 维修单编辑弹窗 -->
<template>
  <div class="ele-body">
    <a-card :title="repairOrderModalApp.title" :bordered="false">
      <a-form
        ref="form2"
        :model="repairOrderModalApp.repairOrder"
        :rules="repairOrderModalApp.rules"
        :label-col="{md: {span: 7}, sm: {span: 24}}"
        :wrapper-col="{md: {span: 17}, sm: {span: 24}}">
        <a-row :gutter="16">

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="报修人:" name="repairApplicantId">
              <m-entity-select
                  :default-value="repairOrderModalApp.repairOrder.repairApplicantName"
                  v-model:value="repairOrderModalApp.repairOrder.repairApplicantId"
                  placeholder="请选择报修人"
                  module="sys"
                  entity="user"
                  :query-filters="{userType:'user'}"
                  system="1"
                  showOptionsName="nickname"
                  class="ele-fluid"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="报修人电话:" name="repairApplicantPhone">
              <a-input
                  v-model:value="repairOrderModalApp.repairOrder.repairApplicantPhone"
                  placeholder="请输入报修电话"
                  :maxlength="255"
                  allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col>
          <a-form-item label="设备:" name="repairApplicantId">
            <m-entity-select
                :default-value="repairOrderModalApp.repairOrder.deviceName"
                v-model:value="repairOrderModalApp.repairOrder.deviceId"
                placeholder="请选择设备"
                module="repairManagement"
                entity="Device"
                showOptionsName="name"
                @getEntityDeviceSelect="selectDevice"
                class="ele-fluid"
            />
          </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="设备类型:" name="repairApplicantPhone">
              <a-input
                  v-model:value="repairOrderModalApp.repairOrder.deviceType"
                  placeholder="请选择设备类型"
                  :maxlength="255"
                  allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="学校:" name="school">
              <a-input
                v-model:value="repairOrderModalApp.repairOrder.school"
                placeholder="请输入学校"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="报修区域:" name="repairArea">
              <m-dict-select
                v-model:value="repairOrderModalApp.repairOrder.repairArea"
                placeholder="请选择报修区域"
                dict="报修区域"/>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="详细位置:" name="detailedLocation">
              <a-input
                v-model:value="repairOrderModalApp.repairOrder.detailedLocation"
                placeholder="请输入详细位置"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="故障类型:" name="faultType">
              <m-dict-select
                v-model:value="repairOrderModalApp.repairOrder.faultType"
                placeholder="请选择故障类型"
                dict="故障类型"/>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="维修时间:" name="expectRepairTime">
              <a-date-picker
                v-model:value="repairOrderModalApp.repairOrder.expectRepairTime"
                placeholder="请选择预期上门维修时间"
                value-format="YYYY-MM-DD H:m:s"
                class="ele-fluid"/>
            </a-form-item>
          </a-col>

<!--          <a-col :lg="6" :md="12" :sm="24" :xs="24">-->
<!--            <a-form-item label="上门维修时间:" name="repairTime">-->
<!--              <a-date-picker-->
<!--                v-model:value="repairOrderModalApp.repairOrder.repairTime"-->
<!--                placeholder="请选择上门维修时间"-->
<!--                value-format="YYYY-MM-DD H:m:s"-->
<!--                class="ele-fluid"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="维修级别:" name="repairLevel">
              <m-dict-select
                v-model:value="repairOrderModalApp.repairOrder.repairLevel"
                placeholder="请选择维修级别"
                dict="维修级别"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="故障描述:" name="remark">
              <a-input
                v-model:value="repairOrderModalApp.repairOrder.remark"
                placeholder="请输入故障描述"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="故障图片:" name="faultPicture">
<!--              <a-input-->
<!--                v-model:value="repairOrderModalApp.repairOrder.faultPicture"-->
<!--                placeholder="请输入故障图片"-->
<!--                :maxlength="255"-->
<!--                allow-clear-->
<!--              />-->

              <image-upload
                :associate-form-id="repairOrderModalApp.repairOrder.eid"
                associate-form-name="repairOrder" ref="imageRef" ></image-upload>
            </a-form-item>
          </a-col>

<!--          <a-col :lg="6" :md="12" :sm="24" :xs="24">-->
<!--            <a-form-item label="当前状态编号:" name="currentState">-->
<!--            </a-form-item>-->
<!--          </a-col>-->

          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
              <!--class="ele-pull-right"-->
              <div v-if="repairOrderModalApp.display">
                <teleport to="#repairOrderEditModalFooter">
                  <div>
                    <a-space size="middle">
                      <a-button @click="repairOrderListApp.editModalShowing=false">取消
                      </a-button>
                      <a-button
                        type="primary"
                        @click="onSubmit(repairOrderModalApp.repairOrder)"
                        :loading="loading">提交
                      </a-button>
                      <!--<a-button v-if="!eid"
                                type="dashed"
                                @click="continueSubmit"
                                :loading="loading">继续提交
                      </a-button>-->
                    </a-space>
                  </div>
                </teleport>
              </div>
              <div v-if="!repairOrderModalApp.display">
                <a-space size="middle">
                  <a-button @click="onBack()">返回列表</a-button>
                  <a-button
                    type="primary"
                    @click="onSubmit(repairOrderModalApp.repairOrder)"
                    :loading="loading">提交
                  </a-button>
                  <!--<a-button v-if="!eid"
                            type="dashed"
                            @click="continueSubmit"
                            :loading="loading">继续提交
                  </a-button>-->
                </a-space>
              </div>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

  </div>

</template>

<script>
import {defineComponent, inject, reactive, onMounted,ref} from 'vue'
import {useRoute, useRouter} from "vue-router"
import {RepairOrderService} from "@/views/repair/repairManagement/repairOrder/repairOrderService";
import {VXETable} from 'vxe-table'
import {useStore} from "vuex";
import regions from 'ele-admin-pro/packages/regions.js';


import MDictSelect from "@/components/MDict/dictSelect";
import MEntitySelect from "@/components/MEntity/entitySelect";
import ImageUpload from "@/components/MImageUpload/ImageUpload";
import attachmentService from "@/components/MFileUpload/attachmentService";
export default defineComponent({
  components: {
    ImageUpload,
    MDictSelect,
    MEntitySelect,
  },
  setup() {
    // 省市区数据
    const cityData = regions
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    const imageRef=ref(null);
    let routeId = route.params.id;
    let repairOrderListApp = inject('repairOrderListApp', reactive({}));
    let repairOrderGrid = inject('repairOrderGrid', reactive({}))
    const repairOrderModalApp = reactive({
      id: null,
      repairOrder: {},
      isEdit: false,
      display: false
    });
    repairOrderModalApp.rules = {
      school: [
        {
          required: true,
          type: 'string',
          message: '请输入学校',
          trigger: 'blur'
        }
      ],
      repairArea: [
        {
          required: true,
          type: 'string',
          message: '请输入报修区域',
          trigger: 'blur'
        }
      ],
      detailedLocation: [
        {
          required: true,
          type: 'string',
          message: '请输入详细位置',
          trigger: 'blur'
        }
      ],
      faultType: [
        {
          required: true,
          type: 'string',
          message: '请输入故障类型',
          trigger: 'blur'
        }
      ],
      repairApplicantName: [
        {
          required: false,
          type: 'string',
          message: '请输入报修人',
          trigger: 'blur'
        }
      ],
      repairApplicantId: [
        {
          required: true,
          type: 'number',
          message: '请输入报修人',
          trigger: 'blur'
        }
      ],
      repairApplicantPhone: [
        {
          required: true,
          type: 'string',
          message: '请输入性别',
          trigger: 'blur'
        }
      ],
      expectRepairTime: [
        {
          required: true,
          type: 'string',
          message: '请输入预期上门维修时间',
          trigger: 'blur'
        }
      ],
      repairTime: [
        {
          required: false,
          type: 'string',
          message: '请输入上门维修时间',
          trigger: 'blur'
        }
      ],
      faultPicture: [
        {
          required: false,
          type: 'string',
          message: '请输入故障图片',
          trigger: 'blur'
        }
      ],
      repairLevel: [
        {
          required: false,
          type: 'string',
          message: '请输入维修级别',
          trigger: 'blur'
        }
      ],
      currentState: [
        {
          required: true,
          type: 'string',
          message: '请输入当前状态编号',
          trigger: 'blur'
        }
      ],
    }

    onMounted(() => {
      //清理数据
      repairOrderModalApp.repairOrder = reactive({});
      if (routeId) {//路由
        repairOrderModalApp.id = routeId;
        repairOrderModalApp.display = false;
        findRepairOrder(repairOrderModalApp.id);
      } else if (repairOrderListApp.editModalForEdit) {//修改弹窗
        repairOrderModalApp.id = repairOrderListApp.currentId;
        repairOrderModalApp.display = true;
      } else if (!repairOrderListApp.editModalForEdit && repairOrderListApp.addModalForEdit) {//新增弹窗
        repairOrderModalApp.display = true;
      } else {
        repairOrderModalApp.title = "新增";
      }
      if (repairOrderModalApp.id) findRepairOrder(repairOrderModalApp.id);
    })

    const findRepairOrder = (id) => {
      RepairOrderService.findRepairOrderForView(id).then((res) => {
        repairOrderModalApp.repairOrder = res.data;
        //TODO:为编辑准备.
        repairOrderModalApp.title = "编辑 " + repairOrderModalApp.repairOrder.name;
      }).catch(error => {
        VXETable.modal.message({content: `查找出错，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:提交 新增&编辑*/
    const onSubmit = (data) => {
      // debugger;
      //当为数组时用逗号连接
      if (data.eid) {
        //修改
        RepairOrderService.updateRepairOrder(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          saveFile(res.data.eid,"repairOrder");
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      } else {
        //新增
        data.currentState=0;
        RepairOrderService.saveRepairOrder(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 3000);
          saveFile(res.data.eid,"repairOrder");
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      }
    }

    /*TODO:继续提交*/
    const continueSubmit = () => {
      VXETable.modal.message({content: 'error 提示', status: 'error'});
    }

    /*TODO:返回列表*/
    const onBack = () => {
      router.push(`/repair/repairManagement/repairOrder`);
      store.dispatch('user/tabRemove', route.fullPath);
      setTimeout(() => {
        repairOrderGrid.value.commitProxy("query");
      }, 1500);
      repairOrderListApp.editModalShowing = false;
    }

    const saveFile = (associateFormId,associateFormName) => {
      // debugger
      console.log("imageRef",imageRef)
      // debugger
      if (imageRef.value.fileList.length !== 0) {
        let formData = new FormData();
        //表单名--对应实体表名
        let formDto = {associateFormId: associateFormId, associateFormName: associateFormName};
        let fileUploadDto = JSON.stringify(formDto)
        formData.append("fileUploadDto", new Blob([fileUploadDto], {type: "application/json"}));
        imageRef.value.fileList.forEach(file => {
          formData.append('files', file)
        });

        attachmentService.saveFile(formData).then(() => {
          imageRef.value.fileList = [];
          VXETable.modal.message({content: '上传成功', status: 'success'});
          //更改上传组件的状态为编辑状态
          // operatorType = "edit";
          // cleanFileList(associateFormId,associateFormName);
        }).catch((error) => {
          // loading.value = false
          VXETable.modal.message({content: '上传失败' + `系统错误，原因是：${error.message}`, status: 'error'});
        });
      }
    }
    const selectDevice = (entity) => {
      console.log(entity)
      repairOrderModalApp.repairOrder.deviceType=entity.type;
      repairOrderModalApp.repairOrder.repairArea=entity.area;
      repairOrderModalApp.repairOrder.detailedLocation=entity.location;
      repairOrderModalApp.repairOrder.deviceName=entity.name;
      repairOrderModalApp.repairOrder.school=entity.useOrganization;
    }
    return {
      cityData,
      routeId,
      repairOrderListApp,
      repairOrderModalApp,
      onSubmit,
      continueSubmit,
      onBack,
      saveFile,
      imageRef,
      selectDevice
    }

  },
})
</script>

<style scoped>

</style>
